package com.lmind.core.async;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.junit.Assert;
import org.junit.Test;

public class FutureResultTestCase {
	
	@Test
	public void test() throws Exception {
		
		ScheduledThreadPoolExecutor schedule = new ScheduledThreadPoolExecutor(5);
		
		final FutureResult<String> result = new FutureResult<String>();

		schedule.schedule(new Runnable() {
			@Override
			public void run() {
				result.done("hello");
			}
		}, 1, TimeUnit.SECONDS);
		
		schedule.shutdown();
		
		Assert.assertEquals("hello", result.get());
	}
	
	@Test
	public void test2() throws Exception {
		
		ScheduledThreadPoolExecutor schedule = new ScheduledThreadPoolExecutor(5);
		
		final FutureResult<String> result = new FutureResult<String>();

		for (int i = 0; i < 3; i++) {
			schedule.submit(new Runnable() {
				@Override
				public void run() {
					try {
						Assert.assertEquals("hello", result.get());
					} catch (Exception e) {
						e.printStackTrace();
						Assert.assertTrue(false);
					}
				}
			});
		}

		Thread.sleep(1000);
		result.done("hello");
		Thread.sleep(1000);
	}
	
	@Test
	public void test3() throws Exception {
		
		ScheduledThreadPoolExecutor schedule = new ScheduledThreadPoolExecutor(5);
		
		final FutureResult<String> result = new FutureResult<String>();

		for (int i = 0; i < 3; i++) {
			schedule.submit(new Runnable() {
				@Override
				public void run() {
					try {
						result.get();
						Assert.assertTrue(false);
					} catch (InterruptedException e) {
						Assert.assertTrue(true);
					} catch (Exception e) {
						e.printStackTrace();
						Assert.assertTrue(false);
					}
				}
			});
		}

		Thread.sleep(1000);
		result.interrupt();
		Thread.sleep(1000);
	}
}
